package com.dididoctor.patient.Activity.OneToOneChat;

import android.content.Context;
import android.graphics.Point;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.dididoctor.patient.Activity.OneToOneChat.rec.RecordPlayer;
import com.dididoctor.patient.Bean.MessageChatBean;
import com.dididoctor.patient.MV.Utils.DisplayUtil;
import com.dididoctor.patient.MV.adapter.CommonAdapter;
import com.dididoctor.patient.MV.adapter.ViewHolder;
import com.dididoctor.patient.R;
import com.dididoctor.patient.Utils.InstallColour;
import com.dididoctor.patient.Utils.LoaderImage;
import com.dididoctor.patient.Utils.UserHeadImage;
import com.dididoctor.patient.Utils.Util;

import java.util.ArrayList;
import java.util.List;


/**
 * 张强
 */
public class OneToOneChatListAdapter_bak extends BaseAdapter {
    protected LayoutInflater mInflater = null;
    protected Context context = null;
    protected List<MessageChatBean> mDatas = null;
    protected final int[] mItemLayoutId;
    private boolean busy = false;

    private LoaderImage loaderImage = null;
    private LoaderImage smallLoaderImage = null;
    private LoaderImage faceLoaderImage = null;
    private ImageView animImageView = null;
    private InstallColour mColors;
    //类型
    private int aniviewType;
    //时间
    private int seconds = 0;

    public OneToOneChatListAdapter_bak(Context context) {
        this.context = context;
        mColors = new InstallColour();
        this.mInflater = LayoutInflater.from(this.context);
        this.faceLoaderImage = new LoaderImage(context, 180, 180, LoaderImage.userHeadImageOptions);
        this.loaderImage = new LoaderImage(context, 256, 256, LoaderImage.chatImageOptions);
        this.smallLoaderImage = new LoaderImage(context, 210, 210, LoaderImage.chatImageOptions);
        //1.左边的文本消息
        //2.右边的文本消息
        //3.左边的图片类型消息
        //4.右边的图片类型消息
        //5.左边的语音消息
        //6.右边的语音消息
        //7.左边的视频
        //8.右边的视频
        //9.题目
        //10.任务
        //11.完成任务
        //12.陪读疑问
        //13.回答疑问消息
        this.mItemLayoutId = new int[]{R.layout.item_chat_text_from, R.layout.item_chat_text_to,
                R.layout.item_chat_image_from, R.layout.item_chat_image_to,
                R.layout.item_chat_voice_from, R.layout.item_chat_voice_to,
                R.layout.item_chatimage_from, R.layout.item_chatimage_to,
                R.layout.item_chat_divers, R.layout.item_new_task_from,
                R.layout.item_finish_task, R.layout.item_chat_question_from, R.layout.item_chat_answer_question_from
        };
    }


    public List<MessageChatBean> getData() {
        return this.mDatas;
    }

    @Override
    public int getCount() {
        if (this.mDatas == null) {
            return 0;
        }
        return mDatas.size();
    }

    @Override
    public MessageChatBean getItem(int position) {
        if (this.mDatas == null) {
            return null;
        }
        return mDatas.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }


    @Override
    public int getViewTypeCount() {
        return this.mItemLayoutId.length;
    }

    /*
    0;//左边的文本消息
    1;//右边的文本消息
    2;//左边的图片消息
    3;//右边的图片消息
    4;//富文本消息
    5;//简单的消息
    */
    @Override
    public int getItemViewType(int position) {
        MessageChatBean message = this.mDatas.get(position);
        return Integer.parseInt(message.getPosition());
    }

    /**
     * 清除数据
     */
    public void clearData() {
        if (this.mDatas != null) {
            this.mDatas.clear();
        }
        notifyDataSetChanged();
    }

    public void addData(MessageChatBean data) {
        if (this.mDatas == null) {
            this.mDatas = new ArrayList<MessageChatBean>();
        }
        this.mDatas.add(data);
        notifyDataSetChanged();
    }

    public void addheaddata(List<MessageChatBean> datas) {
        if (this.mDatas == null) {
            this.mDatas = new ArrayList<MessageChatBean>();
        }
        for (int x = datas.size() - 1; x >= 0; x--) {
            MessageChatBean chatMessage = datas.get(x);
            this.mDatas.add(0, chatMessage);
        }
        notifyDataSetChanged();
    }

    public void addData(List<MessageChatBean> datas) {
        if (this.mDatas == null) {
            this.mDatas = new ArrayList<MessageChatBean>();
        }
        this.mDatas.addAll(datas);
        notifyDataSetChanged();
    }

    public void setData(List<MessageChatBean> datas) {
        this.mDatas = datas;
        notifyDataSetChanged();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        try {
            final ViewHolder viewHolder = getViewHolder(position, convertView, parent);
            convert(position, viewHolder, getItem(position));
            return viewHolder.getConvertView();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    private ViewHolder getViewHolder(int position, View convertView, ViewGroup parent) {
        try {
            return ViewHolder.get(context, convertView, parent, mItemLayoutId[getItemViewType(position)], position);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ViewHolder.get(context, convertView, parent, mItemLayoutId[0], position);
    }

    public void setCommonality(int position, ViewHolder helper, final MessageChatBean item, final int tag) {
        helper.setText(R.id.tv_time, Util.formatDateTime(item.getCreateTime()));

        if (item.isshowTime()) {
            helper.setVisibility(R.id.tv_time, View.VISIBLE);
        } else {
            helper.setVisibility(R.id.tv_time, View.GONE);
        }

        UserHeadImage headImage = helper.getView(R.id.iv_userface);
//        loaderImage.load(headImage, item.getfId());
        headImage.UserHeadShow(); // 必须调用才能显示

        headImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Intent intent = null;
//                String stuID = null;
//                if (tag == 0) { // 左边
//                    stuID = item.getSenduid();
//                    intent = new Intent(context, MyZoneAccompanyActivity.class);
//                    intent.putExtra("stuID", stuID);
//                    Bundle bundle = ((AccompanyChatActivity) context).getBundle();
//                    intent.putExtras(bundle);
//                    context.startActivity(intent);
//                } else if (tag == 1) { // 右边
//                    stuID = Token.getUserId();
//                    intent = new Intent(context, MyZoneActivity.class);
//                    intent.putExtra("userId", Token.getUserId());
//                    intent.putExtra("isChat", true);
//                    return;
//                }
                //intent.putExtra("orderID", item.getOrderID());
                //intent.putExtra("stuID", stuID);
                //Bundle bundle = ((AccompanyChatActivity)context).getBundle();
                //intent.putExtras(bundle);
                //context.startActivity(intent);
            }
        });
    }

    public void convert(int position, ViewHolder helper, final MessageChatBean item) {

        switch (getItemViewType(position)) {
            //左边文本0
            case MessageChatBean.LEFT_TEXT: {
                setCommonality(position, helper, item, 0);
                helper.setText(R.id.tv_content, item.getContent());
                helper.setText(R.id.tv_userName, item.getSenduName());//发送人的名字
                break;
            }

            //右边文本1
            case MessageChatBean.RIGHT_TEXT: {
                setCommonality(position, helper, item, 1);
                helper.setText(R.id.tv_content, item.getContent());
                helper.setText(R.id.tv_userName, item.getSenduName());//发送人的名字
                break;
            }


            //左边图片2
            case MessageChatBean.LEFT_IMG: {
                setCommonality(position, helper, item, 0);

                //图片消息
                ImageView imageContent = (ImageView) helper.getView(R.id.iv_imageContent);
                if (imageContent != null) {
                    //            imageContent.setOnClickListener(new ImageContentOnClockListener(item.getObjectId()));
                }
                helper.setText(R.id.tv_userName, item.getSenduName());//发送人的名字
                this.loaderImage.load(imageContent, item.getfId());
                final String imgId = item.getfId();
                if ("".equals(imgId) && imgId != null) {

                    helper.getView(R.id.iv_imageContent).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
//                            Intent intent = new Intent(context, PicScanActivity.class);
//                            ArrayList<String> arr = new ArrayList<String>();
//                            arr.add(imgId);
//                            intent.putStringArrayListExtra("img_urls", arr);
//                            context.startActivity(intent);
                        }
                    });
                }
                break;
            }

            //右边图片3
            case MessageChatBean.RIGHT_IMG: {
                setCommonality(position, helper, item, 1);

                //图片消息
                ImageView imageContent = helper.getView(R.id.iv_imageContent);
                if (imageContent != null) {
//                                imageContent.setOnClickListener(new ImageContentOnClockListener(item.getObjectId()));
                }
                helper.setText(R.id.tv_userName, item.getSenduName());//发送人的名字
                this.loaderImage.load(imageContent, item.getfId());
                final String imgId = item.getfId();
                if ("".equals(imgId) && imgId != null) {

                    helper.getView(R.id.iv_imageContent).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
//                            Intent intent = new Intent(context, PicScanActivity.class);
//                            ArrayList<String> arr = new ArrayList<String>();
//                            arr.add(imgId);
//                            intent.putStringArrayListExtra("img_urls", arr);
//                            context.startActivity(intent);
                        }
                    });
                }
                break;
            }


            //左边语音4
            case MessageChatBean.LEFT_VOICE: {
                setCommonality(position, helper, item, 0);
//                helper.setText(R.id.tv_userName, item.getSendUserName());//发送人的名字
                ImageView animactionleft = helper.getView(R.id.tv_content);
                final LinearLayout layout = helper.getView(R.id.ll_voice_content);
                animactionleft.setOnClickListener(new RecordOnclickListener(item));
                //语音消息动画
                animactionleft.setImageResource(R.drawable.voice_a_left);
                final TextView tv_time = helper.getView(R.id.play_time_left);
                tv_time.post(new Runnable() {
                    @Override
                    public void run() {
                        int timeWidth = tv_time.getWidth();
                        setViewWidth(layout, item, timeWidth);//修改控件的宽度
                        tv_time.setText(seconds + "\"");
                    }
                });

                break;
            }

            //右边语音5
            case MessageChatBean.RIGHT_VOICE: {
                setCommonality(position, helper, item, 1);
//                helper.setText(R.id.tv_userName, item.getSendUserName());//发送人的名字
                ImageView animactionright = helper.getView(R.id.tv_content);
                final LinearLayout layout = helper.getView(R.id.ll_voice_content);
                animactionright.setOnClickListener(new RecordOnclickListener(item));
                animactionright.setImageResource(R.drawable.voice_a_right);
                final TextView tv_time = helper.getView(R.id.play_time_right);
                tv_time.post(new Runnable() {
                    @Override
                    public void run() {
                        int timeWidth = tv_time.getWidth();
                        setViewWidth(layout, item, timeWidth);//修改控件的宽度
                        tv_time.setText("\"" + seconds);
                    }
                });
                break;
            }
        }
    }

    /**
     * 修改控件宽度
     *
     * @param view
     * @param item
     */
    private void setViewWidth(View view, MessageChatBean item) {
        try {
            String[] arg = item.getContent().split(":");
            if (arg.length < 2) {
                return;
            }
            if (arg[1].endsWith("s")) {
                arg[1] = arg[1].substring(0, arg[1].length() - 1);
            }
            seconds = Integer.parseInt(arg[1]);
            Point point = DisplayUtil.getScreenMetrics(context);
            ViewGroup.LayoutParams params = view.getLayoutParams();
            params.width = (int) ((point.x * 0.2f) + (seconds / 60f * (point.x * 0.4f)) * 0.75f);
            view.setLayoutParams(params);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void setViewWidth(View view, MessageChatBean item, int timeWidth) {
        try {
            String[] arg = item.getContent().split(":");
            if (arg.length < 2) {
                return;
            }
            if (arg[1].endsWith("s")) {
                arg[1] = arg[1].substring(0, arg[1].length() - 1);
            }
            seconds = Integer.parseInt(arg[1]);
            Point point = DisplayUtil.getScreenMetrics(context);
            ViewGroup.LayoutParams params = view.getLayoutParams();
            int finalWidth = (int) ((point.x * 0.2f) + (seconds / 60f * (point.x * 0.4f)));
            int margin = (int) context.getResources().getDimension(R.dimen.DIMEN_50PX);
            if (finalWidth + margin + timeWidth + 100 >= point.x) {
                params.width = point.x - margin - timeWidth - 100;
            } else {
                params.width = finalWidth;
            }
            view.setLayoutParams(params);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //语音点击事件
    public class RecordOnclickListener implements View.OnClickListener {
        private MessageChatBean chatMessage = null;

        public RecordOnclickListener(MessageChatBean chatMessage) {
            this.chatMessage = chatMessage;
        }

        @Override
        public void onClick(View v) {
            final int viewType = Integer.parseInt(chatMessage.getPosition());
            if (animImageView == null) {//没有播放过
                animImageView = (ImageView) v;
                aniviewType = viewType;
                if (viewType == MessageChatBean.LEFT_VOICE) {//左边的语音消息
                    animImageView.setImageResource(R.drawable.down_voice_list_left);
                } else if (viewType == MessageChatBean.RIGHT_VOICE) {//右边的语音消息
                    animImageView.setImageResource(R.drawable.down_voice_list_right);
                }
                ((AnimationDrawable) animImageView.getDrawable()).start();
                RecordPlayer.paly(chatMessage.getfId(), new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        //释放资源
                        RecordPlayer.release();
                        if (aniviewType == MessageChatBean.LEFT_VOICE) {
                            animImageView.setImageResource(R.drawable.voice_a_left);
                        } else if (aniviewType == MessageChatBean.RIGHT_VOICE) {
                            animImageView.setImageResource(R.drawable.voice_a_right);
                        }
                        animImageView = null;
                    }
                });
            } else {//有语音正在播放
                String tag = (String) animImageView.getTag();
                if (tag != null && tag.equals(chatMessage.getfId())) {//如果点击的是同一个
                    if (RecordPlayer.isPlay()) {//如果是正在播放状态
                        if (viewType == MessageChatBean.LEFT_VOICE) {//左边的语音消息
                            animImageView.setImageResource(R.drawable.voice_a_left);
                        } else if (viewType == MessageChatBean.RIGHT_VOICE) {//右边的语音消息
                            animImageView.setImageResource(R.drawable.voice_a_right);
                        }
                        RecordPlayer.release();
                    } else {//如果是播放暂停状态
                        if (viewType == MessageChatBean.LEFT_VOICE) {//左边的语音消息
                            animImageView.setImageResource(R.drawable.down_voice_list_left);
                        } else if (viewType == MessageChatBean.RIGHT_VOICE) {//右边的语音消息
                            animImageView.setImageResource(R.drawable.down_voice_list_right);
                        }
                        ((AnimationDrawable) animImageView.getDrawable()).start();
                        RecordPlayer.paly(chatMessage.getfId(), new MediaPlayer.OnCompletionListener() {
                            @Override
                            public void onCompletion(MediaPlayer mp) {
                                //释放资源
                                RecordPlayer.release();
                                if (aniviewType == MessageChatBean.LEFT_VOICE) {
                                    animImageView.setImageResource(R.drawable.voice_a_left);
                                } else if (aniviewType == MessageChatBean.RIGHT_VOICE) {
                                    animImageView.setImageResource(R.drawable.voice_a_right);
                                }
                                animImageView = null;
                            }
                        });
                    }
                } else {//点击不一样的语音
                    Log.d("aaaa", "播放中点击不一样的语音");
                    if (aniviewType == MessageChatBean.LEFT_VOICE) {
                        animImageView.setImageResource(R.drawable.voice_a_left);
                    } else if (aniviewType == MessageChatBean.RIGHT_VOICE) {
                        animImageView.setImageResource(R.drawable.voice_a_right);
                    }

                    animImageView = (ImageView) v;
                    aniviewType = viewType;
                    if (viewType == MessageChatBean.LEFT_VOICE) {//左边的语音消息
                        animImageView.setImageResource(R.drawable.down_voice_list_left);
                    } else if (viewType == MessageChatBean.RIGHT_VOICE) {//右边的语音消息
                        animImageView.setImageResource(R.drawable.down_voice_list_right);
                    }
                    ((AnimationDrawable) animImageView.getDrawable()).start();
                    RecordPlayer.paly(chatMessage.getfId(), new MediaPlayer.OnCompletionListener() {
                        @Override
                        public void onCompletion(MediaPlayer mp) {
                            //释放资源
                            RecordPlayer.release();
                            if (aniviewType == MessageChatBean.LEFT_VOICE) {
                                animImageView.setImageResource(R.drawable.voice_a_left);
                            } else if (aniviewType == MessageChatBean.RIGHT_VOICE) {
                                animImageView.setImageResource(R.drawable.voice_a_right);
                            }
                            animImageView = null;
                        }
                    });
                }
            }
            animImageView.setTag(chatMessage.getfId());
        }
    }

    class ImageGridAdapter extends CommonAdapter<String> {

        public ImageGridAdapter(Context context, List<String> datas, int itemLayoutId) {
            super(context, datas, itemLayoutId);
        }

        @Override
        public void convert(final int position, ViewHolder helper, String item) {
            ImageView imageView = helper.getView(R.id.iv_imageContent);
            if (!TextUtils.isEmpty(item)) {
                imageView.setVisibility(View.VISIBLE);
//                loaderImage.load(imageView, ResBox.appServiceResource(item));
            } else {
                imageView.setVisibility(View.GONE);
            }
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
//                    Intent intent = new Intent(context, PicScanActivity.class);
//                    intent.putStringArrayListExtra("img_urls", (ArrayList<String>) datas);
//                    intent.putExtra("position", position);
//                    context.startActivity(intent);
//                    ActivityAnimationUtils.startnewActivity((AccompanyChatActivity) context);
                }
            });
        }
    }
}

